<template>
    <div class="wrapper">
        <el-form :inline="true">
            <el-form-item>
                <el-dropdown @command="setState">
                    <span class="el-dropdown-link">
                        {{stateStr}}
                        <i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item :command="{title:'全部状态',id:''}">全部状态</el-dropdown-item>
                        <el-dropdown-item :command="{title:'启用',id:'1'}">启用</el-dropdown-item>
                        <el-dropdown-item :command="{title:'禁用',id:'2'}">禁用</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </el-form-item>
            <el-form-item>
                <el-input placeholder="请输入会议编码/会议协议名称"
                    style="width:300px;"
                    v-model="search"
                    clearable></el-input>
            </el-form-item>
            <el-form-item class="fr">
                <el-button size="small"
                    type="primary"
                    @click="_add"
                    v-has="'pricemeetingset'">
                    新 增
                </el-button>
            </el-form-item>
            <el-form-item>
                <el-button size="small"
                    type="primary"
                    @click="_search">
                    <i class="el-icon-search"
                        style="width:30px"></i>
                </el-button>
            </el-form-item>
            <el-form-item>
                <el-table :data="headList">
                    <el-table-column label="编码"
                        prop="num">
                    </el-table-column>
                    <el-table-column label="名称"
                        prop="name">
                    </el-table-column>
                    <el-table-column label="描述"
                        prop="describes">
                    </el-table-column>
                    <el-table-column label="状态">
                        <template slot-scope="scope">
                            {{scope.row.state == 1? '启动': '禁用'}}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button type="text"
                                size="small"
                                @click="edit(scope.row)"
                                v-has="'pricemeetingset'">修改</el-button>
                            <el-button type="text"
                                v-if="scope.row.state == 1 && scope.row.chuncui != 1"
                                size="small"
                                @click="_deleteMeetingPrice(2,scope.row.id)"
                                v-has="'pricemeetingonoff'">禁用</el-button>
                            <el-button type="text"
                                v-if="scope.row.state == 2"
                                size="small"
                                @click="_deleteMeetingPrice(1,scope.row.id)"
                                v-has="'pricemeetingonoff'">启用</el-button>
                            <el-button type="text"
                                size="small"
                                v-if="scope.row.chuncui != 1"
                                @click="_deleteMeetingPrice(3,scope.row.id)"
                                v-has="'pricemeetingdelete'">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item class="fr">
                <el-pagination @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pageNum"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
            </el-form-item>
        </el-form>
        <!-- 新增编辑弹窗 -->
        <el-dialog :title="title"
            :visible.sync="dialogVisible"
            width="1200px">
            <el-form label-width="120px"
                class="dialog">
                <el-form-item label="会议编码："
                    required>
                    <el-input placeholder="请输入会议编码"
                        maxlength="30"
                        clearable
                        v-model="formData.num"></el-input>
                </el-form-item>
                <el-form-item label="会议协议名称："
                    required>
                    <el-input placeholder="请输入会议协议名称"
                        maxlength="30"
                        clearable
                        v-model="formData.name"></el-input>
                </el-form-item>
                <el-form-item label="会议协议：">
                    <el-input placeholder="请输入会议协议"
                        v-model="formData.describe"
                        maxlength="50"
                        type="textarea"
                        clearable
                        style="width:300px"></el-input>
                </el-form-item>
                <el-form-item label="是否门市价：">
                    <el-radio-group v-model="formData.chuncui"
                        :disabled="formData.meetings.length>0 || chuncui ==1">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="2">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="折扣类型："
                    v-if="formData.chuncui == 2">
                    <el-radio-group v-model="formData.type"
                        :disabled="formData.meetings.length>0">
                        <el-radio :label="1">按比率折扣</el-radio>
                        <el-radio :label="2">按折扣价格</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary"
                        size="small"
                        class="fr"
                        @click="_addRoomPrice">新增会议厅价格</el-button>
                </el-form-item>
                <el-table style="margin-top:20px"
                    :data="formData.meetings">
                    <el-table-column label="会议厅"
                        prop="meetingName">
                    </el-table-column>
                    <el-table-column :label="head.label"
                        v-for="(head, key) in header"
                        :key="key">
                        <template slot-scope="scope">
                            {{formData.meetings[scope.$index][head.key]}}
                            <span v-if="head.key =='discountRate'">%</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="启用时间"
                        prop="startTime">
                    </el-table-column>
                    <el-table-column label="操作"
                        width="200">
                        <template slot-scope="scope">
                            <el-button type="text"
                                size="small"
                                @click="editRoomPrice(formData.meetings[scope.$index],scope.$index)">修改</el-button>
                            <el-button type="text"
                                size="small"
                                @click="_setFestival(formData.meetings[scope.$index].festivals,scope.$index)">节日价格设置</el-button>
                            <el-button type="text"
                                size="small"
                                @click="formData.meetings.splice(scope.$index,1)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <Log :logList="logList" />
            </el-form>
            <span slot="footer"
                class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary"
                    @click="_sure">保存</el-button>
            </span>
        </el-dialog>
        <!-- 新增房型价格 -->
        <el-dialog :title="title"
            :visible.sync="dialogRoomPrice"
            width="400px">
            <el-form label-width="110px">
                <el-form-item label="会议厅："
                    required>
                    <el-select v-model="room.meetingId"
                        @change="selectRoomType">
                        <el-option v-for="(item,index) in meetingTypeList"
                            :key="index"
                            :label="item.roomName"
                            :value="item.roomId"
                            :disabled="item.disabled"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="全天价格："
                    required>
                    <!-- <el-input placeholder="请输入全天价格"
                  v-model="room.chuncuiMoney"
                  :disabled="formData.chuncui !=1"></el-input> -->
                    <el-input-number v-model="room.chuncuiMoney"
                        controls-position="right"
                        size="small"
                        :disabled="formData.chuncui !=1"
                        :min="0"
                        :precision="2"
                        :max="10000"></el-input-number>
                </el-form-item>
                <div v-if="formData.chuncui !=1">
                    <el-form-item label="折后价格："
                        required
                        v-if="formData.type == 2 ">
                        <!-- <el-input placeholder="请输入折后价格"
                     clearable
                     maxlength="5"
                     v-model="room.discountMoney"
                     @keyup.native="room.discountMoney=room.discountMoney.replace(/[\u4e00-\u9fa5]/ig,'')"
                     v-number-only></el-input> -->
                        <el-input-number v-model="room.discountMoney"
                            controls-position="right"
                            size="small"
                            :min="0"
                            :precision="2"
                            :max="10000"></el-input-number>
                    </el-form-item>
                    <div v-if="formData.type == 1">
                        <el-form-item label="折扣比率："
                            required>
                            <!-- <el-input placeholder="请输入折扣比率"
                        style="width:80%"
                        v-model="room.discountRate"
                        @keyup.native="room.discountRate=room.discountRate.replace(/[\u4e00-\u9fa5]/ig,'')"
                        v-number-only
                        clearable
                        maxlength="4"></el-input> -->
                            <el-input-number v-model="room.discountRate"
                                controls-position="right"
                                size="small"
                                :min="0"
                                :precision="2"
                                :max="100"></el-input-number>
                            <span>%</span>
                        </el-form-item>
                        <el-form-item label="折后价格："
                            v-if="room.discountRate && room.chuncuiMoney">
                            ￥
                            <span>{{sum}}</span>
                        </el-form-item>
                    </div>
                </div>
            </el-form>
            <span slot="footer"
                class="dialog-footer">
                <el-button @click="dialogRoomPrice = false">取 消</el-button>
                <el-button type="primary"
                    @click="_sureRoomPrice">保存</el-button>
            </span>
        </el-dialog>
        <!-- 节假日设置弹窗 -->
        <el-dialog title="节假日设置"
            :visible.sync="dialogVisibleFestival"
            width="800px">
            <el-form>
                <el-form-item>
                    <el-table :data="festivaList">
                        <el-table-column label="起始时间 - 终止时间"
                            width="260">
                            <template slot-scope="scope">
                                <el-date-picker v-model="scope.row.startEndTime"
                                    size="small"
                                    value-format="yyyy-MM-dd"
                                    type="daterange"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    @change="setTime"
                                    end-placeholder="结束日期">
                                </el-date-picker>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name"
                            label="折扣类型">
                            <template slot-scope="scope">
                                <el-select v-model="scope.row.type">
                                    <el-option label="按比率"
                                        :value="1"></el-option>
                                    <el-option label="按价格"
                                        :value="2"></el-option>
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name"
                            width="200"
                            label="房价">
                            <template slot-scope="scope">
                                <el-input-number v-model="scope.row.roomPrice"
                                    controls-position="right"
                                    size="small"
                                    :min="0"
                                    :max="10000"
                                    :precision="2"
                                    v-show="scope.row.type==2"></el-input-number>
                                <el-input-number v-model="scope.row.roomPrice"
                                    controls-position="right"
                                    size="small"
                                    :min="0"
                                    :max="100"
                                    :precision="2"
                                    v-show="scope.row.type==1"></el-input-number>&nbsp;&nbsp;
                                <span v-show="scope.row.type==1"> %</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name"
                            label="操作">
                            <template slot-scope="scope">
                                <el-button size="mini"
                                    type="primary"
                                    v-if="scope.$index == festivaList.length-1"
                                    @click="_addFestival">
                                    +
                                </el-button>
                                <el-button size="mini"
                                    @click="_reduceFestival(scope.$index)">
                                    -
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
            </el-form>
            <span slot="footer"
                class="dialog-footer">
                <el-button @click="dialogVisibleFestival = false">取 消</el-button>
                <el-button type="primary"
                    @click="_sureFestival">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {
  getMeetingList,
  updateMeetingPrice,
  deleteMeetingPrice,
  getMeetingTypeList,
  getMeetingDetail,
  getMeetingLog
} from "@/public/js/price.js";
import Log from "./log";
import { format } from "@/public/js/util";
export default {
  components: {
    Log
  },
  props: {},
  data() {
    return {
      stateStr: "全部状态",
      state: "",
      pageNum: 1,
      pageSize: 10,
      search: "",
      total: 0,
      headList: [],
      dialogVisible: false,
      dialogRoomPrice: false,
      dialogVisibleFestival: false,
      title: "新增协议会议价",
      chuncui: 1,
      logList: [],
      pickerOptions: {},
      //新增 房型数据
      room: {
        id: "",
        meetingId: "",
        meetingName: "",
        chuncuiMoney: "",
        discountRate: "",
        discountMoney: "",
        startTime: "",
        festivals: []
      },
      meetingTypeList: [],
      formData: {
        id: "",
        num: "",
        name: "",
        describe: "",
        chuncui: 2,
        type: 1,
        meetings: []
      },
      header: [
        {
          label: "正常全天价格",
          key: "chuncuiMoney"
        }
      ],
      __index: "",
      festivaList: [],
      formFestivaList: [],
      handle_index: "",
      isAddRoomPrice: true
    };
  },

  watch: {
    formData: {
      handler(newVal) {
        // 全天价格格
        if (newVal.chuncui == 1) {
          this.header = [
            {
              label: "全天价格",
              key: "chuncuiMoney"
            }
          ];
        } else if (newVal.chuncui == 2) {
          //按比例折扣
          if (newVal.type == 1) {
            this.header = [
              {
                label: "全天价格",
                key: "chuncuiMoney"
              },
              {
                label: "折扣比率",
                key: "discountRate"
              },
              {
                label: "折后价格",
                key: "discountMoney"
              }
            ];
          } else if (newVal.type == 2) {
            this.header = [
              {
                label: "全天价格",
                key: "chuncuiMoney"
              },
              {
                label: "折后价格",
                key: "discountMoney"
              }
            ];
          }
        }
      },
      deep: true
    }
  },
  computed: {
    sum() {
      this.room.discountMoney =
        parseFloat(this.room.chuncuiMoney) *
        parseFloat(this.room.discountRate) /
        100;
      return isNaN(this.room.discountMoney)
        ? ""
        : this.room.discountMoney.toFixed(2);
    }
  },
  methods: {
    //时间选择
    setTime(time) {
      this.pickerOptions.disabledDate = function disabledDate(time) {
        console.log(time);
        return time.getTime() < Date.now() - 8.64e7;
      };
    },
    //状态查询
    setState(data) {
      this.stateStr = data.title;
      this.state = data.id;
      this.pageNum = 1;
      this.pageSize = 10;
      this._getMeetingList();
    },
    // 搜索
    _search() {
      this.pageNum = 1;
      this.pageSize = 10;
      this._getMeetingList();
    },
    // 获取列表数据
    _getMeetingList() {
      getMeetingList({
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        state: this.state,
        search: this.search
      }).then(res => {
        console.log("res", res);
        this.headList = res.data.headList;
        this.total = res.data.total;
        this.chuncui = res.data.chuncui;
      });
    },
    // 新增
    _add() {
      this.title = "新增协议会议价";
      this.formData = {
        id: "",
        num: "",
        name: "",
        describe: "",
        chuncui: 2,
        type: 1,
        meetings: []
      };
      this._getMeetingTypeList();
      this.dialogVisible = true;
    },
    //编辑
    edit(row) {
      console.log(row);
      this._getMeetingDetail(row.id);
      this._getMeetingLog(row.id);
    },
    //获取 详情数据
    _getMeetingDetail(id) {
      getMeetingDetail({ id: id }).then(res => {
        let priceMeetingHead = res.data.priceMeetingHead;
        console.log("priceMeetingHead", res);
        this.title = "编辑协议会议价";
        this.formData = {
          id: priceMeetingHead.id,
          num: priceMeetingHead.priceNum,
          name: priceMeetingHead.priceName,
          describe: priceMeetingHead.describes,
          chuncui: priceMeetingHead.chuncui,
          type: priceMeetingHead.discountType,
          meetings: []
        };
        priceMeetingHead.priceMeetings.forEach((item, index) => {
          let festivals = [];
          item.festivalInfos.forEach(i => {
            festivals.push({
              id: i.id,
              startEndTime: [i.startTime, i.endTime],
              type: i.discountType,
              roomPrice: i.roomPrice
            });
          });

          this.formData.meetings.push({
            id: item.id,
            meetingId: item.meetingId,
            meetingName: item.meetingName,
            chuncuiMoney: item.chuncuiMoney,
            discountRate: item.discountRate,
            discountMoney: item.discountMoney,
            startTime: item.startTime,
            festivals: festivals
          });
        });
        console.log(" this.formData", this.formData);
        this._getMeetingTypeList();
        this.dialogVisible = true;
      });
    },
    //选择房型
    selectRoomType(meetingId) {
      this.meetingTypeList.forEach((item, index) => {
        if (item.roomId == meetingId) {
          this.room.chuncuiMoney = item.money;
          this.room.meetingName = item.roomName;
          this.__index = index;
        }
      });
      console.log(this.room);
    },
    // 设置节日
    _setFestival(festivaList, _index) {
      this.handle_index = _index;
      if (!festivaList.length) {
        this.festivaList = [
          {
            id: "",
            startEndTime: [],
            type: 1,
            roomPrice: ""
          }
        ];
      } else {
        this.festivaList = festivaList;
      }
      this.dialogVisibleFestival = true;
    },

    // 新增 节日数据
    _addFestival() {
      this.festivaList.push({
        id: "",
        startEndTime: [],
        type: 1,
        roomPrice: ""
      });
    },
    // 删除 节日数据
    _reduceFestival(__index) {
      this.festivaList.splice(__index, 1);
    },
    // 设置节日保存
    _sureFestival() {
      //表单验证
      console.log("this.festivaList", this.festivaList);
      let flag = false;
      this.festivaList.forEach(item => {
        if (!item.startEndTime.length) {
          this.$message.error("请输入开始时间结束时间");
          flag = true;
          return false;
        } else if (!item.roomPrice) {
          this.$message.error("请输入房价");
          flag = true;
          return false;
        }
      });
      if (!flag) {
        this.formData.meetings[this.handle_index].festivals = this.festivaList;
        this.dialogVisibleFestival = false;
      }
    },
    _deleteMeetingPrice(state, id) {
      let info = "";
      if (state == 3) {
        info = "是否删除该条数据?";
      } else if (state == 1) {
        info = "是否启用该条数据?";
      } else {
        info = "是否禁用用该条数据?";
      }
      this.$confirm(info, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteMeetingPrice({
          id: id,
          state: state
        }).then(res => {
          if (!res.data.errCode) {
            this.$message({
              message: "操作成功",
              type: "success"
            });
            this._getMeetingList();
          }
        });
      });
    },
    //获取房型列表
    _getMeetingTypeList() {
      getMeetingTypeList().then(res => {
        this.meetingTypeList = res.data.roomTypeList;
        console.log("this.meetingTypeList", this.meetingTypeList);
        this.meetingTypeList.forEach(item => {
          this.formData.meetings.forEach(i => {
            if (i.meetingId == item.roomId) {
              item.disabled = true;
            }
          });
        });
      });
    },
    // 新增房型价格
    _addRoomPrice() {
      this._getMeetingTypeList();
      this.isAddRoomPrice = true;
      this.dialogRoomPrice = true;
      this.title = "新增会议厅价格";
      this.room = {
        id: "",
        meetingId: "",
        meetingName: "",
        chuncuiMoney: "",
        discountRate: "",
        discountMoney: "",
        startTime: format(new Date().getTime(), "yyyy-MM-dd"),
        festivals: []
      };
    },
    // 修改房型价格
    editRoomPrice(data, __index) {
      this._getMeetingTypeList();
      this.isAddRoomPrice = false;
      this.handle_index = __index;
      this.dialogRoomPrice = true;
      this.title = "修改会议厅价格";
      this.room = JSON.parse(JSON.stringify(data));
    },
    //保存
    _sure() {
      // 表单验证
      this._updateMeetingPrice();
    },
    // 保存新增房型价格
    _sureRoomPrice() {
      //表单验证
      if (!this.room.meetingId) {
        this.$message.error("请选择会议厅");
        return false;
      }
      if (!this.room.chuncuiMoney) {
        this.$message.error("请输入全天价格格");
        return false;
      }
      //非全天价格
      if (this.formData.chuncui == 2) {
        if (this.formData.type == 1) {
          if (!this.room.discountRate) {
            this.$message.error("请输折扣率");
            return false;
          }
        } else if (this.formData.type == 2) {
          if (!this.room.discountMoney) {
            this.$message.error("请输折后价格");
            return false;
          }
          if (this.room.discountMoney > this.room.chuncuiMoney) {
            this.$message.error("输折后价格不能大于全天价格");
            return false;
          }
        }
      }
      if (this.isAddRoomPrice) {
        this.formData.meetings.push(this.room);
      } else {
        let room = this.formData.meetings[this.handle_index];
        room.chuncuiMoney = this.room.chuncuiMoney;
        room.discountMoney = this.room.discountMoney;
        room.discountRate = this.room.discountRate;
        room.meetingId = this.room.meetingId;
        room.meetingName = this.room.meetingName;
      }
      this.dialogRoomPrice = false;
    },
    // 新增编辑
    _updateMeetingPrice() {
      let data = JSON.parse(JSON.stringify(this.formData));
      data.meetings.forEach(item => {
        item.festivals.forEach(i => {
          i.startTime = i.startEndTime[0];
          i.endTime = i.startEndTime[1];
          delete i.startEndTime;
        });
      });

      // 表单验证
      if (!data.num) {
        this.$message.error("请输入会议编码");
        return false;
      } else if (!data.name) {
        this.$message.error("请输入会议协议名称");
        return false;
      }
      console.log("this.data", data);
      // 表单验证
      updateMeetingPrice(data).then(res => {
        if (!res.data.errCode) {
          this.$message({
            message: "操作成功",
            type: "success"
          });
          this.dialogVisible = false;
          this._getMeetingList();
        }
      });
    },
    //获取日志信息
    _getMeetingLog(id) {
      getMeetingLog({ id: id }).then(res => {
        console.log(res);
        this.logList = res.data.logs;
      });
    },
    // 分页
    handleSizeChange(val) {
      this.pageSize = val;
      this._getMeetingList();
    },
    handleCurrentChange() {
      this.pageNum = val;
      this._getMeetingList();
    }
  },
  created() {
    this._getMeetingList();
  },
  mounted() {}
};
</script>
<style lang="scss" scoped>
.wrapper {
  .dialog {
    .el-input {
      width: 300px;
    }
  }
  .cell {
    display: inline-block;
  }
  .el-range-editor--small {
    width: 100%;
  }
}
</style>